package com.example.springbootdockertest.controller.async;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * Async 测试
 *
 * @Author liguangcheng
 * @Date 2021/10/12 11:28 上午
 * @Vision 1.0
 **/
@RestController
public class AsyncController {
    @Autowired
    private AsyncTest asyncTest;
    @Autowired
    ApplicationContext applicationContext;

    //本类调用 无效情况
    @GetMapping("/async")
    public String async() {
        System.out.println("Invoking an asynchronous method. "
                + Thread.currentThread().getName());
        asyncTest();
        System.out.println("结束");
        return "结束";
    }

    //本类调用 有效情况
    @GetMapping("/async1")
    public String async1() {
        System.out.println("Invoking an asynchronous method. "
                + Thread.currentThread().getName());
        applicationContext.getBean(AsyncController.class).asyncTest();
        System.out.println("结束");
        return "结束";
    }


    @Async
    public void asyncTest() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            //
        }
        System.out.println(StrUtil.format("execute async,currentThread-->{}", Thread.currentThread().getName()));
    }

    //有返回值的情况
    @GetMapping("/async2")
    public void testAsyncAnnotationForMethodsWithReturnType()
            throws InterruptedException, ExecutionException {
        System.out.println("Invoking an asynchronous method. "
                + Thread.currentThread().getName());
        String s = "hello world !!!!";

        Future future = asyncTest.asyncMethodWithReturnType(s);
        while (true) {
            if (future.isDone()) {
                System.out.println("Result from asynchronous process - " + future.get());
                break;
            }
            System.out.println("Continue doing something else. ");
            Thread.sleep(1000);
        }
    }

    //无返回值情况
    @GetMapping("/async3")
    public void testAsyncAnnotationForMethodsWithVoidType() {
        System.out.println("Invoking an asynchronous method. "
                + Thread.currentThread().getName());
        String s = "hello world !!!!";

        asyncTest.asyncMethodWithVoidType(s);

    }

}
